const fs = require("fs");
const path = require("path");
// 引入 events 模块
var events = require('events');
// 创建 eventEmitter 对象
var eventEmitter = new events.EventEmitter();
eventEmitter.on('writeFile', function (file, data) {
  fs.writeFileSync(file, data);
});
eventEmitter.on('copyFile', async function (fromFileName, toFileName) {
  let readStream = await fs.createReadStream(fromFileName);
  let writeStream = await fs.createWriteStream(toFileName);
  readStream.pipe(writeStream);
});
function readFile (filePath) {
  return Promise(function (resolve, reject) {
    fs.readFile(filePath, 'utf8', function (err, data) {
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}

function writeFile (src, fileName, data) {
  return new Promise((resolve, reject) => {
    try {
      //判断路径文件夹是否存在
      fs.accessSync(src);
    } catch (err) {
      try {
        //不存在创建文件夹
        fs.mkdirSync(src)
      } catch (error) {
        //创建失败
        reject(error)
      }
    }
    //完整文件路径
    let _cache_file = path.resolve(src, fileName);
    //写文件
    fs.writeFile(_cache_file, data, (err) => {
      if (err) {
        reject(err)
      } else {
        resolve(_cache_file)
      }
    });
  });
}
// fs.writeFileSync(file, data);
module.exports = {
  readFile,
  writeFile,
  eventEmitter,
}
